<template>
	<view class="info-upload">
		<view class="container">
			<uni-forms :modelValue="formData" :rules="rules" ref="formRef">
				<uni-forms-item label="停车指引" name="tps" required>
					<!-- <uni-file-picker v-model="imageValue" limit="9" title="最多选择9张图片" fileMediatype="image" mode="grid" -->
					<uni-file-picker v-model="imageValue" fileMediatype="image" mode="grid" @select="select" />
				</uni-forms-item>

				<uni-forms-item label="标题" name="title" required>
					<uni-easyinput type="text" v-model="formData.title" placeholder="请输入标题" />
				</uni-forms-item>


				<uni-forms-item label="地理位置" name="zb" required>
					<map style="width: 100%; height: 200px;" :latitude="mapAddress.latitude"
						:longitude="mapAddress.longitude" :markers="covers" @click="changeMapHandle()">
					</map>
				</uni-forms-item>

				<uni-forms-item label="省市区" name="ssq" required>
					<uni-data-picker :localdata="cityData" popup-title="请选择区域" :map="cityDict"
						@change="handleChangeCity">
					</uni-data-picker>
				</uni-forms-item>

				<uni-forms-item label="详细地址" name="address" required>
					<uni-easyinput type="textarea" v-model="formData.address" placeholder="请输入详细地址" />
				</uni-forms-item>

				<uni-forms-item label="是否支持充电" name="sfcd" label-width="120px" required>
					<uni-data-checkbox v-model="isCharge" :localdata="charge" @change="isChargeChange">
					</uni-data-checkbox>
				</uni-forms-item>

				<uni-forms-item label="收费模式" name="sfmsArray" label-width="120px" required>
					<uni-data-checkbox multiple v-model="isChargModel" :localdata="chargModel"
						@change="isChargModelChange"></uni-data-checkbox>
				</uni-forms-item>

				<uni-forms-item label="停车类型" name="tclxArray" label-width="120px" required>
					<uni-data-checkbox multiple v-model="stopCarType" :localdata="stopCar" @change="stopCarTyleChange">
					</uni-data-checkbox>
				</uni-forms-item>

				<uni-forms-item label="月卡价格" name="prices" required>
					<uni-easyinput type="number" v-model="formData.prices" placeholder="请输入月卡价格" />
				</uni-forms-item>

				<uni-forms-item label="临时价格" name="provisionaPrice">
					<uni-easyinput type="number" v-model="formData.provisionaPrice" placeholder="请输入临时价格" />
				</uni-forms-item>

				<uni-forms-item label="停车备注" name="descs" required>
					<uni-easyinput type="text" v-model="formData.descs" placeholder="请输入停车备注信息" />
				</uni-forms-item>

			</uni-forms>

			<view class="button">
				<text class="footer-text" @click="submit('formRef')">提交</text>
			</view>

		</view>
	</view>
</template>

<script>
	import {baseURL} from '@/common/request.js'
	import cityPicker from './city-picker/city-picker.vue'
	import {
		upLoadInfo,
		upDateInfo,
		regionList
	} from '@/api/parkInfo.js'
	export default {
		components: {
			'city-picker': cityPicker
		},
		data() {
			return {
				imageValue: [],
				cityData: [],
				cityDict: {
					text: 'label',
					value: 'value'
				},
				mapAddress: {
					latitude: '',
					longitude: ''
				},
				covers: [{
					id: 0,
					latitude: 0,
					longitude: 0,
					iconPath: require('@/static/location.png'),
				}],
				upData: {},
				formData: {
					title: "", // 标题
					ssq: [], // 省市区
					address: "", // 详细地址
					descs: "", // 停车备注
					prices: 0, // 月卡价格
					provisionaPrice: 0, // 临时价格
					sfcd: '', // 是否充电  0是支持 1是不支持 2不知道
					sfmsArray: [], // 收费模式
					tclxArray: [], // 停车类型 室内室外
					tps: [], // 上传的图片？
					zb: "" // 坐标
				},
				isCharge: '',
				charge: [{
					text: '是',
					value: 0
				}, {
					text: '否',
					value: 1
				}, {
					text: '不知道',
					value: '2'
				}],
				isChargModel: [],
				chargModel: [{
					text: '月卡',
					value: 'yk',
				}, {
					text: '临时停车',
					value: 'lstc'
				}],
				stopCarType: [],
				stopCar: [{
					text: '室内',
					value: 'sn'
				}, {
					text: '室外',
					value: 'sw'
				}],

				rules: {
					title: {
						rules: [{
							required: true,
							errorMessage: '请输入标题',
						}, ]
					},
					zb: {
						rules: [{
							required: true,
							errorMessage: '请点击地图选择详细地址',
						}, ]
					},
					ssq: {
						rules: [{
								format: 'array'
							},
							{
								validateFunction: function(rule, value, data, callback) {
									if (value.length == 0) {
										callback('请选择省市区')
									}
									return true
								}
							}
						]
					},
					address: {
						rules: [{
							required: true,
							errorMessage: '请输入详细地址',
						}, ]
					},
					descs: {
						rules: [{
							required: true,
							errorMessage: '请输入停车备注',
						}, ]
					},
					prices: {
						rules: [{
							required: true,

						}, {
							validateFunction: function(rule, value, data, callback) {
								if (value == 0) {
									callback('请输入月卡价格')
								}
								return true
							}
						}]
					},
					// provisionaPrice: {
					// 	rules: [{
					// 		required: true,

					// 	}, {
					// 		validateFunction: function(rule, value, data, callback) {
					// 			if (value == '') {
					// 				callback('请输入临时价格')
					// 			}
					// 			return true
					// 		}
					// 	}]
					// },
					sfmsArray: {
						rules: [{
								format: 'array'
							},
							{
								validateFunction: function(rule, value, data, callback) {
									if (value.length == 0) {
										callback('请添加收费模式')
									}
									return true
								}
							}
						]
					},
					sfcd: {
						rules: [{
							required: true,
							errorMessage: '请选择是否可以充电',
						}, ]
					},
					tclxArray: {
						rules: [{
								format: 'array'
							},
							{
								validateFunction: function(rule, value, data, callback) {
									if (value.length == 0) {
										callback('请添加停车类型')
									}
									return true
								}
							}
						]
					},
					tps: {
						rules: [{
								format: 'array'
							},
							{
								validateFunction: function(rule, value, data, callback) {
									if (value.length < 1) {
										callback('请添加上传图片')
									}
									return true
								}
							}
						]
					},
				}
			}
		},
		onLoad(options) {
			wx.setStorageSync('change_addr', '')
			const location = uni.getStorageSync('location')
			this.mapAddress = location
			this.covers[0].latitude = location.latitude
			this.covers[0].longitude = location.longitude
			// console.log("onload---this.mapAddress: ", this.mapAddress);
			// console.log("onload---this.covers: ", this.covers[0]);

			regionList().then((res) => {
				this.cityData = res.data;
				console.log('this.cityData', this.cityData);
			});


			if (options.upData) {
				const data = JSON.parse(decodeURIComponent(options.upData))
				console.log('修改数据-data', data);
				this.formData = data
				this.imageValue.push(...data.tps)  
				
				const addr = data.zb.split(',')
				this.mapAddress.latitude = addr[1]
				this.mapAddress.longitude = addr[0]
				
				// this.formData.ssq = e.detail.value.map(v => v.value)
				// this.formData.ssq = data.ssq
				
				// this.stopCarType = data.tclxText 
				// this.formData.tclxArray = e.detail.data.map(v => v.value)
			}
		},
		onShow() {
			const addr = uni.getStorageSync('change_addr')
			if (addr) {
				this.mapAddress = JSON.parse(addr)
				this.covers[0].latitude = this.mapAddress.latitude
				this.covers[0].longitude = this.mapAddress.longitude
				this.formData.zb = `${this.mapAddress.longitude},${this.mapAddress.latitude}`
			}
		},
		onReady() {
			// 设置自定义表单校验规则，必须在节点渲染完毕后执行
			this.$refs.formRef.setRules(this.rules)
		},
		onUnload() {
			wx.setStorageSync('change_addr', '')
		},
		methods: {
			handleChangeCity(e) {
				// const [province, city, county] = e.detail.value;
				this.formData.ssq = e.detail.value.map(v => v.value)
				console.log("e.detail.value: ", e.detail.value);
				// console.log("province: ", province);
				// console.log("city: ", city);
				// console.log("county ", county);
			},

			// // 获取上传状态
			select(chooseImageRes) {
				console.log('选择文件：', chooseImageRes)
				const tempFilePaths = chooseImageRes.tempFilePaths;
				const that = this
				const url = baseURL.slice(0,-3).replace('/b','//b')
				console.log("url: ",url);
				uni.uploadFile({
					url: url+'/upload/cloud',
					filePath: tempFilePaths[0],
					name: 'file',
					formData: {
						'user': 'test'
					},
					success: (uploadFileRes) => {
						const data = JSON.parse(uploadFileRes.data)
						console.log('上传成功', data.data)
						that.formData.tps.push(data.data)
						console.log('that.formData.tps', that.formData.tps)

					},
					fail(err) {
						console.log("err: ", err);
					}
				});
			},

			// 是否支持充电
			isChargeChange(e) {
				console.log('是否支持充电e:', e.detail.data);
				this.formData.sfcd = e.detail.data.value
			},
			// 收费模式
			isChargModelChange(e) {
				console.log('收费模式e:', e.detail.data);
				this.formData.sfmsArray = []
				this.formData.sfmsArray = e.detail.data.map(v => v.value)
			},
			// 停车类型
			stopCarTyleChange(e) {
				console.log('停车类型e:', e);
				this.formData.tclxArray = []
				this.formData.tclxArray = e.detail.data.map(v => v.value)
			},

			changeMapHandle() {
				uni.chooseLocation({
					success: function(res) {
						if (!res.name) return
						console.log("选中该地址-res: ", res);
						console.log('位置名称：' + res.name);
						console.log('详细地址：' + res.address);
						console.log('纬度：' + res.latitude);
						console.log('经度：' + res.longitude);
						wx.setStorageSync('change_addr', JSON.stringify({
							longitude: res.longitude,
							latitude: res.latitude,
						}))
						this.mapAddress = res
						console.log("当前选择的: ", this.mapAddress);
					},
					fail: function(err) {

						console.log("changeMapHandle--err: ", err);
					},

				});
			},

			onchange(e) {
				const value = e.detail.value
				console.log("value: ", value);
			},
			onnodeclick(node) {
				console.log("node: ", node);
			},

			async submit(ref) {
				const res = await this.$refs.formRef.validate()
				if (res) {
					console.log("res: ", res);
					console.log("this.formData: ", this.formData);
					let response
					if (this.upData) {
						console.log("9527: ", this.formData);
						return
						response = await upDateInfo(this.formData)
					} else {
						console.log("9528: ", this.formData);
						return
						response = await upLoadInfo(this.formData)
					}
					console.log("response: ", response);
					return
					if (response.code == 0) {
						wx.setStorageSync('change_addr', '')
						uni.showToast({
							title: this.upData ? "修改成功" : '新增成功'
						})
						// uni.navigateBack({
						// 	delta: 1
						// })
						setTimeout(() => {
							uni.navigateTo({
								url: '/pages/subPack/info-share/info-share'
							})
						}, 200)

					}
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	/deep/.uni-forms-item__label {
		padding: 0 !important;
	}

	/deep/.uni-forms-item__content {
		display: flex;
		align-items: center;
	}

	/deep/.checklist-box {
		margin-right: 0 !important;
	}

	.info-upload {
		width: 100%;
		background: #fff;
		box-sizing: border-box;
		padding: 15px;
		position: relative;

		.header {
			text-align: center;
			padding: 10px 0;
		}

		.button {
			padding-bottom: 30rpx;

			>.footer-text {
				height: 40px;
				line-height: 40px;
				display: block;
				border-radius: 10px;
				// background: #a7dc39;
				background: #03beff;
				text-align: center;
				width: 345px;
				text-align: center;
				color: white;
			}
		}
	}
</style>
